<?php
namespace Mouta\AmistateBundle\Entity;

use FOS\UserBundle\Entity\UserManager as BaseUserManager;
use Mouta\AmistateBundle\Entity\ImagenUsuario;
use Mouta\AmistateBundle\utils\Strings;
use Mouta\AmistateBundle\utils\SfSolr;


class UserManager extends BaseUserManager
{
    /**
     * Finds a user by username
     *
     * @param string $username
     * @return UserInterface
     */
    public function findUserByUsername($username)
    {
        $user = $this->repository->getFullUserByEmail($username);
        if($user && $user->isEnabled())
            return $user;
        else
            return null;
    }
    
    public function saveImage(ImagenUsuario $image){
        $this->em->persist($image);
        $this->em->flush();
    }
    
    public function actualizarUser($user){
        $tagsUsuario = $user->getTags();
        $tagsUsuario->clear();
        $em = $this->em;
        $tags = $em->getRepository('AmistateBundle:Tags')->generateTags($user);
        foreach($tags as $t){
            $user->addTags($t);
        }
        $user->setSeoPais(Strings::getSeoUrl($user->getPais()));
        $user->setSeoProvincia(Strings::getSeoUrl($user->getProvincia()));
        $user->setSeoCiudad(Strings::getSeoUrl($user->getCiudad()));
        if($user->getVerificado())
        {
            $solr = new SfSolr();
            $solr->AddOrUpdateUser($user);
        }
        if($user->getBorrado())
        {
            $solr = new SfSolr();
            $solr->DeleteUser($user);
        }
        $em->persist($user);
        $em->flush();
        
        parent::updateUser($user);
    }
    
    public function getUserById($id){
        return $this->em->getRepository('AmistateBundle:Usuario')->findOneBy(array('id'=>$id));
    }
}
